class FurnitureLogisticStatOrderItem < ActiveRecord::Base
  
  validates :order_item_id,
    :furniture_logistic_stat_id,
    :presence => true
  validates :order_item_id,
    :uniqueness => {
      :scope => :furniture_logistic_stat_id
    }  
  validates :ordered_count, 
    :numericality => {
      :greater_than_or_equal_to => 1
    },
    :on => :create
  validates :has_been_sent_to_installer_count,
    :installed_count,
    :after_serviced_count,
    :numericality => {
      :greater_than_or_equal_to => 0
    }
  
  belongs_to :order_item
  belongs_to :enter_item
  belongs_to :furniture_logistic_stat  
  
  
  after_save do |stat_and_order_item|  
    order_item.reset_ordered_count! if order_item.is_a?(OrderItem::SpotsOrdered)
    furniture_logistic_stat.reset_ordered_count!
    furniture_logistic_stat.reset_sold_count!
  end
  
  after_destroy do |stat_and_order_item|  
    order_item.reset_ordered_count! if order_item.is_a?(OrderItem::SpotsOrdered)
    furniture_logistic_stat.reset_ordered_count!
  end
  
  def furniture
    furniture_logistic_stat.furniture
  end
  
  def order
    order_item.order
  end
  
  # 可安装数
  def can_be_installed_count
    ordered_count - has_been_sent_to_installer_count - installed_count
  end
  
  # 重置已派工数
  def reset_has_been_sent_to_installer_count!
    update_attribute :has_been_sent_to_installer_count, InstallItem.where("install_items.furniture_logistic_stat_order_item_id = ? ", id).has_been_sent_to_installer.sum('install_items.has_been_sent_to_installer_count')
  end
  
  # 重置已安装数
  def reset_installed_count!
#    install_items = InstallItem.where("install_items.furniture_logistic_stat_order_item_id = ?", id).includes(:feed)
#    install_items.each do |item|
#      logger.debug "item.feed.id=====#{item.feed.id}    item.feed.type======#{item.feed.type}   item.installed_count=======#{item.installed_count}"
#    end
#    Feed.all.each do |feed|
#      logger.debug "feed.id=====#{feed.id}    feed.type======#{feed.type}"
#    end

    inst_count = InstallItem.where("install_items.furniture_logistic_stat_order_item_id = ?", id).over.sum('install_items.installed_count')
    logger.debug "inst_count=======#{inst_count}"
    update_attribute :installed_count, inst_count
  end
  
end
